package com.yyr.callmessage.core.global;


import com.yyr.callmessage.core.constant.SystemError;
import com.yyr.callmessage.core.ro.BaseRo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Profile;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * controller未处理异常全局捕获处理
 */
@ControllerAdvice
@Slf4j
@Profile("dev")
public class GlobalExceptionHandleDev {

    /**
     * 全局错误处理捕获
     * @param exception 异常类
     * @return BaseRo
     */
//    @ExceptionHandler(Exception.class)
//    @ResponseBody
//    public BaseRo handle(Exception exception) {
//        return process(SystemError.ProcessCode, exception.getMessage());
//    }

    /**
     * 单独设置参数验证错误捕获，Get方式
     * @param exception 异常类
     * @return BaseRoG
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public BaseRo validationHandle(BindException exception) {
        FieldError error = (FieldError)exception.getBindingResult().getAllErrors().get(0);
        return process(SystemError.ProcessCode, error.getDefaultMessage());
    }

    /**
     * 单独设置参数验证错误捕获,Post方式
     * @param exception 异常类
     * @return BaseRo
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public BaseRo validationHandle1(MethodArgumentNotValidException exception) {
        FieldError error = (FieldError)exception.getBindingResult().getAllErrors().get(0);
        return process(SystemError.ProcessCode, error.getDefaultMessage());
    }

    private BaseRo process(String code, String msg) {
        log.error(msg);
        return new BaseRo(code, msg, false);
    }
}
